package com.luoxiang.orderclient;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import com.alibaba.fastjson.JSON;
import com.luoxiang.register.LxState;
import com.luoxiang.register.ZookeeperRegister;

public class OrderClient implements Watcher{

	ZookeeperRegister register = new ZookeeperRegister();
	
	private String clientName;

	public String getClientName() {
		return clientName;
	}

	public void setClientName(String clientName) {
		this.clientName = clientName;
	}
	
	public void subscribe(String clientName) {
		ZooKeeper zooKeeper = register.getConnection(this);
		try {
			Thread.sleep(10000);
			List<String> nodeList = zooKeeper.getChildren(ZookeeperRegister.ROOT, true);
			System.out.println(nodeList);
			if(nodeList.isEmpty()) {
				throw new RuntimeException("没有会员系统服务");
			}
			for(String node : nodeList) {
				System.out.println(node);
				byte[] data = zooKeeper.getData(ZookeeperRegister.ROOT+"/"+node, true, null);
				LxState state = JSON.parseObject(new String(data), LxState.class);
				System.out.println(state);
				if(state != null && ("init".equals(state.getStatus())) ) {
					state.setNode(node);
					state.setStatus("run");
					state.setClientName(clientName);
					zooKeeper.setData(ZookeeperRegister.ROOT+"/"+state.getNode(), JSON.toJSONString(state).getBytes(), -1);
				}else {
					System.out.println("没有找到可用run服务");
				}
			}
		} catch (KeeperException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void process(WatchedEvent event) {
		// TODO Auto-generated method stub
		
	}
	
	public static void main(String[] args) throws IOException {
		OrderClient client = new OrderClient();
		client.setClientName("交易系统01");
		client.subscribe(client.getClientName());
		System.in.read();
	}
}
